package com.peng.herostory.cmdhanlder;

import com.peng.herostory.login.LoginService;
import com.peng.herostory.model.MoveState;
import com.peng.herostory.model.User;
import com.peng.herostory.model.UserManager;
import com.peng.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户登陆指令处理器
 */
public class UserLoginCmdHandler implements ICmdHandler<GameMsgProtocol.UserLoginCmd> {
    /**
     * 日志对象
     */
    static private final Logger LOGGER = LoggerFactory.getLogger(UserLoginCmdHandler.class);

    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserLoginCmd cmd) {
        if (null == ctx ||
                null == cmd) {
            return;
        }

        String userName = cmd.getUserName();
        String password = cmd.getPassword();

        LOGGER.info(
                "用户登陆, userName = {}, password = {}",
                userName,
                password
        );


        try {
            LoginService.getInstance().userLogin(
                    userName, password, (userEntity) -> {
                        if (null == userEntity) {
                            LOGGER.error("用户登陆失败, userName = {}", cmd.getUserName());
                            return;
                        }

                        LOGGER.info(
                                "用户登陆成功, userId = {}, userName = {}",
                                userEntity.userId,
                                userEntity.userName
                        );

                        // 新建用户,
                        User newUser = new User(userEntity.userId, userEntity.userName, userEntity.heroAvatar, 100, new MoveState(), false);
                        // 并将用户加入管理器
                        UserManager.addUser(newUser);

                        // 将用户 Id 附着到 Channel
                        ctx.channel().attr(AttributeKey.valueOf("userId")).set(newUser.getUserId());

                        // 登陆结果构建者
                        GameMsgProtocol.UserLoginResult.Builder
                                resultBuilder = GameMsgProtocol.UserLoginResult.newBuilder();
                        resultBuilder.setUserId(newUser.getUserId());
                        resultBuilder.setUserName(newUser.getUserName());
                        resultBuilder.setHeroAvatar(newUser.getHeroAvatar());


                        // 构建结果并发送
                        GameMsgProtocol.UserLoginResult newResult = resultBuilder.build();
                        ctx.writeAndFlush(newResult);

                    }
            );
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }


    }
}
